package com.coursehub.user.controller;

import com.coursehub.shared.dto.ApiResponse;
import com.coursehub.user.dto.LoginResponseDto;
import com.coursehub.user.dto.UserLoginDto;
import com.coursehub.user.entity.User;
import com.coursehub.user.service.UserService;
import com.coursehub.user.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponseDto>> login(@Valid @RequestBody UserLoginDto loginDto) {
        log.info("用户登录请求: {}", loginDto.getUserAccount());
        User user = userService.login(loginDto);
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUserAccount(), user.getUserName());
        LoginResponseDto loginResponse = new LoginResponseDto(token, user);
        
        return ResponseEntity.ok(ApiResponse.success("登录成功", loginResponse));
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout() {
        userService.logout();
        return ResponseEntity.ok(ApiResponse.success("注销成功"));
    }
}